package com.ktjiaoyu.ktmall.servlet.admin;
/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */

import com.alibaba.fastjson.JSON;
import com.ktjiaoyu.ktmall.entity.AdminUser;
import com.ktjiaoyu.ktmall.service.AdminUserService;
import com.ktjiaoyu.ktmall.service.impl.AdminUserServiceImpl;
import com.ktjiaoyu.ktmall.utils.R;
import com.ktjiaoyu.ktmall.utils.SysConstants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * LoginServlet业务控制器
 *
 * @author 科泰集团教研团队
 * @version 1.0.0
 * @createTime 2024-4-9 17:36:33
 * @lastModify 2024-4-9 17:36:33
 */
@WebServlet(name = "LoginServlet", urlPatterns = "/api/login")
public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String username = request.getParameter("username");
        String password = request.getParameter("password");


        AdminUserService AdminUserService = new AdminUserServiceImpl();
        // 登录
        AdminUser loginAdmin = AdminUserService.login(username, password);

        R result = null;
        if(loginAdmin != null){
            // 存入session前，去掉密码
            loginAdmin.setPassword(null);
            // 登录成功,存放登录用户到session中
            session.setAttribute(SysConstants.SESSION_LOGIN_ADMIN, loginAdmin);
            // 返回成功
            result = R.ok(loginAdmin);
        }else{
            result = R.fail().msg("登录失败，用户名或密码错误！");
        }
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
